using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using XEvolve.Core.Runtime.Internal;

namespace XEvolve.Core.Runtime.PluginProviders
{
    public class PluginFolder : IPluginProvider
    {
        private readonly string pluginFolder;

        public PluginFolder() : this(Path.Combine(Environment.CurrentDirectory, "Plugins"))
        {
        }

        public PluginFolder(string pluginFolder)
        {
            this.pluginFolder = pluginFolder;
        }

        public Type[] Plugins
        {
            get
            {
                if (!Directory.Exists(pluginFolder)) return new Type[0];
                var plugins = new List<Type>();
                foreach (var file in Directory.GetFiles(pluginFolder))
                {
                    if (!file.EndsWith(".dll", true, CultureInfo.CurrentCulture)) continue;
                    try
                    {
                        var assembly = Assembly.LoadFile(file);
                        var pluginInAssembly = assembly.GetExportedTypes().Where(type => type.IsPluginType());
                        foreach (var pluginType in pluginInAssembly)
                        {
                            plugins.Add(pluginType);
                        }
                    }
                    catch
                    {
                    }
                }
                return plugins.ToArray();
            }
        }
    }
}